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