]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-address.el
emacs: address: allow internal completion on an individual basis
[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")
41
42 (defcustom notmuch-address-command 'internal
43   "Determines how address completion candidates are generated.
44
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.
48
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
52 this case.
53
54 Finally, if this variable is nil then address completion is
55 disabled."
56   :type '(radio
57           (const :tag "Use internal address completion" internal)
58           (const :tag "Disable address completion" nil)
59           (string :tag "Use external completion command"))
60   :group 'notmuch-send
61   :group 'notmuch-external)
62
63 (defcustom notmuch-address-internal-completion '(sent nil)
64   "Determines how internal address completion generates candidates.
65
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
71  to the query."
72   :type '(list :tag "Use internal address completion"
73                (radio
74                 :tag "Base completion on messages you have"
75                 :value sent
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))
87   :group 'notmuch-send
88   :group 'notmuch-external)
89
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."
97   :type 'function
98   :group 'notmuch-send
99   :group 'notmuch-external)
100
101 (defun notmuch-address-selection-function (prompt collection initial-input)
102   "Call (`completing-read'
103       PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
104   (completing-read
105    prompt collection nil nil initial-input 'notmuch-address-history))
106
107 (defvar notmuch-address-completion-headers-regexp
108   "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
109
110 (defvar notmuch-address-history nil)
111
112 (defun notmuch-address-message-insinuate ()
113   (message "calling notmuch-address-message-insinuate is no longer needed"))
114
115 (defcustom notmuch-address-use-company t
116   "If available, use company mode for address completion"
117   :type 'boolean
118   :group 'notmuch-send)
119
120 (defun notmuch-address-setup ()
121   (let* ((setup-company (and notmuch-address-use-company
122                            (require 'company nil t)))
123          (pair (cons notmuch-address-completion-headers-regexp
124                        #'notmuch-address-expand-name)))
125       (when setup-company
126         (notmuch-company-setup))
127       (unless (memq pair message-completion-alist)
128         (setq message-completion-alist
129               (push pair message-completion-alist)))))
130
131 (defun notmuch-address-toggle-internal-completion ()
132   "Toggle use of internal completion for current buffer.
133
134 This overrides the global setting for address completion and
135 toggles the setting in this buffer."
136   (interactive)
137   (if (local-variable-p 'notmuch-address-command)
138       (kill-local-variable 'notmuch-address-command)
139     (setq-local notmuch-address-command 'internal))
140   (if (boundp 'company-idle-delay)
141       (if (local-variable-p 'company-idle-delay)
142           (kill-local-variable 'company-idle-delay)
143         (setq-local company-idle-delay nil))))
144
145 (defun notmuch-address-matching (substring)
146   "Returns a list of completion candidates matching SUBSTRING.
147 The candidates are taken from `notmuch-address-completions'."
148   (let ((candidates)
149         (re (regexp-quote substring)))
150     (maphash (lambda (key val)
151                (when (string-match re key)
152                  (push key candidates)))
153              notmuch-address-completions)
154     candidates))
155
156 (defun notmuch-address-options (original)
157   "Returns a list of completion candidates. Uses either
158 elisp-based implementation or older implementation requiring
159 external commands."
160   (cond
161    ((eq notmuch-address-command 'internal)
162     (when (not notmuch-address-full-harvest-finished)
163       ;; First, run quick synchronous harvest based on what the user
164       ;; entered so far
165       (notmuch-address-harvest original t))
166     (prog1 (notmuch-address-matching original)
167       ;; Then start the (potentially long-running) full asynchronous harvest if necessary
168       (notmuch-address-harvest-trigger)))
169    (t
170     (process-lines notmuch-address-command original))))
171
172 (defun notmuch-address-expand-name ()
173   (cond
174    ((and (eq notmuch-address-command 'internal)
175          notmuch-address-use-company
176          (bound-and-true-p company-mode))
177     (company-manual-begin))
178    (notmuch-address-command
179     (let* ((end (point))
180            (beg (save-excursion
181                   (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
182                   (goto-char (match-end 0))
183                   (point)))
184            (orig (buffer-substring-no-properties beg end))
185            (completion-ignore-case t)
186            (options (with-temp-message "Looking for completion candidates..."
187                       (notmuch-address-options orig)))
188            (num-options (length options))
189            (chosen (cond
190                     ((eq num-options 0)
191                      nil)
192                     ((eq num-options 1)
193                      (car options))
194                     (t
195                      (funcall notmuch-address-selection-function
196                               (format "Address (%s matches): " num-options)
197                               (cdr options) (car options))))))
198       (if chosen
199           (progn
200             (push chosen notmuch-address-history)
201             (delete-region beg end)
202             (insert chosen))
203         (message "No matches.")
204         (ding))))
205    (t nil)))
206
207 ;; Copied from `w3m-which-command'.
208 (defun notmuch-address-locate-command (command)
209   "Return non-nil if `command' is an executable either on
210 `exec-path' or an absolute pathname."
211   (when (stringp command)
212     (if (and (file-name-absolute-p command)
213              (file-executable-p command))
214         command
215       (setq command (file-name-nondirectory command))
216       (catch 'found-command
217         (let (bin)
218           (dolist (dir exec-path)
219             (setq bin (expand-file-name command dir))
220             (when (or (and (file-executable-p bin)
221                            (not (file-directory-p bin)))
222                       (and (file-executable-p (setq bin (concat bin ".exe")))
223                            (not (file-directory-p bin))))
224               (throw 'found-command bin))))))))
225
226 (defun notmuch-address-harvest-addr (result)
227   (let ((name-addr (plist-get result :name-addr)))
228     (puthash name-addr t notmuch-address-completions)))
229
230 (defun notmuch-address-harvest-handle-result (obj)
231   (notmuch-address-harvest-addr obj))
232
233 (defun notmuch-address-harvest-filter (proc string)
234   (when (buffer-live-p (process-buffer proc))
235     (with-current-buffer (process-buffer proc)
236       (save-excursion
237         (goto-char (point-max))
238         (insert string))
239       (notmuch-sexp-parse-partial-list
240        'notmuch-address-harvest-handle-result (process-buffer proc)))))
241
242 (defvar notmuch-address-harvest-procs '(nil . nil)
243   "The currently running harvests.
244
245 The car is a partial harvest, and the cdr is a full harvest")
246
247 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
248   "Collect addresses completion candidates.
249
250 It queries the notmuch database for messages sent/received (as
251 configured with `notmuch-address-command`) by the user, collects
252 destination/source addresses from those messages and stores them
253 in `notmuch-address-completions'.
254
255 If ADDR-PREFIX is not nil, only messages with to/from addresses
256 matching ADDR-PREFIX*' are queried.
257
258 Address harvesting may take some time so the address collection runs
259 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
260 execution, CALLBACK is called when harvesting finishes."
261
262   (let* ((sent (eq (car notmuch-address-internal-completion) 'sent))
263          (config-query (cadr notmuch-address-internal-completion))
264          (prefix-query (when addr-prefix
265                          (format "%s:%s*" (if sent "to" "from") addr-prefix)))
266          (from-or-to-me-query
267           (mapconcat (lambda (x)
268                        (concat (if sent "from:" "to:") x))
269                      (notmuch-user-emails) " or "))
270          (query (if (or prefix-query config-query)
271                     (concat (format "(%s)" from-or-to-me-query)
272                             (when prefix-query
273                               (format " and (%s)" prefix-query))
274                             (when config-query
275                               (format " and (%s)" config-query)))
276                   from-or-to-me-query))
277          (args `("address" "--format=sexp" "--format-version=2"
278                  ,(if sent "--output=recipients" "--output=sender")
279                  "--deduplicate=address"
280                  ,query)))
281     (if synchronous
282         (mapc #'notmuch-address-harvest-addr
283                                    (apply 'notmuch-call-notmuch-sexp args))
284       ;; Asynchronous
285       (let* ((current-proc (if addr-prefix
286                                (car notmuch-address-harvest-procs)
287                              (cdr notmuch-address-harvest-procs)))
288              (proc-name (format "notmuch-address-%s-harvest"
289                                 (if addr-prefix "partial" "full")))
290              (proc-buf (concat " *" proc-name "*")))
291         ;; Kill any existing process
292         (when current-proc
293           (kill-buffer (process-buffer current-proc))) ; this also kills the process
294
295         (setq current-proc
296               (apply 'notmuch-start-notmuch proc-name proc-buf
297                      callback                           ; process sentinel
298                      args))
299         (set-process-filter current-proc 'notmuch-address-harvest-filter)
300         (set-process-query-on-exit-flag current-proc nil)
301         (if addr-prefix
302             (setcar notmuch-address-harvest-procs current-proc)
303           (setcdr notmuch-address-harvest-procs current-proc)))))
304   ;; return value
305   nil)
306
307 (defun notmuch-address-harvest-trigger ()
308   (let ((now (float-time)))
309     (when (> (- now notmuch-address-last-harvest) 86400)
310       (setq notmuch-address-last-harvest now)
311       (notmuch-address-harvest nil nil
312                                (lambda (proc event)
313                                  ;; If harvest fails, we want to try
314                                  ;; again when the trigger is next
315                                  ;; called
316                                  (if (string= event "finished\n")
317                                      (setq notmuch-address-full-harvest-finished t)
318                                    (setq notmuch-address-last-harvest 0)))))))
319
320 ;;
321
322 (defun notmuch-address-from-minibuffer (prompt)
323   (if (not notmuch-address-command)
324       (read-string prompt)
325     (let ((rmap (copy-keymap minibuffer-local-map))
326           (omap minibuffer-local-map))
327       ;; Configure TAB to start completion when executing read-string.
328       ;; "Original" minibuffer keymap is restored just before calling
329       ;; notmuch-address-expand-name as it may also use minibuffer-local-map
330       ;; (completing-read probably does not but if something else is used there).
331       (define-key rmap (kbd "TAB") (lambda ()
332                                      (interactive)
333                                      (let ((enable-recursive-minibuffers t)
334                                            (minibuffer-local-map omap))
335                                        (notmuch-address-expand-name))))
336       (let ((minibuffer-local-map rmap))
337         (read-string prompt)))))
338
339 ;;
340
341 (provide 'notmuch-address)
342
343 ;;; notmuch-address.el ends here