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