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