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