]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-address.el
emacs: Remove notmuch-setq-local
[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 finished.
40 Use notmuch-address--harvest-ready to access as that will load a
41 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 ;; Copied from `w3m-which-command'.
254 (defun notmuch-address-locate-command (command)
255   "Return non-nil if `command' is an executable either on
256 `exec-path' or an absolute pathname."
257   (and (stringp command)
258        (if (and (file-name-absolute-p command)
259                 (file-executable-p command))
260            command
261          (setq command (file-name-nondirectory command))
262          (catch 'found-command
263            (let (bin)
264              (dolist (dir exec-path)
265                (setq bin (expand-file-name command dir))
266                (when (or (and (file-executable-p bin)
267                               (not (file-directory-p bin)))
268                          (and (file-executable-p (setq bin (concat bin ".exe")))
269                               (not (file-directory-p bin))))
270                  (throw 'found-command bin))))))))
271
272 (defun notmuch-address-harvest-addr (result)
273   (let ((name-addr (plist-get result :name-addr)))
274     (puthash name-addr t notmuch-address-completions)))
275
276 (defun notmuch-address-harvest-handle-result (obj)
277   (notmuch-address-harvest-addr obj))
278
279 (defun notmuch-address-harvest-filter (proc string)
280   (when (buffer-live-p (process-buffer proc))
281     (with-current-buffer (process-buffer proc)
282       (save-excursion
283         (goto-char (point-max))
284         (insert string))
285       (notmuch-sexp-parse-partial-list
286        'notmuch-address-harvest-handle-result (process-buffer proc)))))
287
288 (defvar notmuch-address-harvest-procs '(nil . nil)
289   "The currently running harvests.
290
291 The car is a partial harvest, and the cdr is a full harvest.")
292
293 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
294   "Collect addresses completion candidates.
295
296 It queries the notmuch database for messages sent/received (as
297 configured with `notmuch-address-command`) by the user, collects
298 destination/source addresses from those messages and stores them
299 in `notmuch-address-completions'.
300
301 If ADDR-PREFIX is not nil, only messages with to/from addresses
302 matching ADDR-PREFIX*' are queried.
303
304 Address harvesting may take some time so the address collection runs
305 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
306 execution, CALLBACK is called when harvesting finishes."
307   (let* ((sent (eq (car notmuch-address-internal-completion) 'sent))
308          (config-query (cadr notmuch-address-internal-completion))
309          (prefix-query (and addr-prefix
310                             (format "%s:%s*"
311                                     (if sent "to" "from")
312                                     addr-prefix)))
313          (from-or-to-me-query
314           (mapconcat (lambda (x)
315                        (concat (if sent "from:" "to:") x))
316                      (notmuch-user-emails) " or "))
317          (query (if (or prefix-query config-query)
318                     (concat (format "(%s)" from-or-to-me-query)
319                             (and prefix-query
320                                  (format " and (%s)" prefix-query))
321                             (and config-query
322                                  (format " and (%s)" config-query)))
323                   from-or-to-me-query))
324          (args `("address" "--format=sexp" "--format-version=4"
325                  ,(if sent "--output=recipients" "--output=sender")
326                  "--deduplicate=address"
327                  ,query)))
328     (if synchronous
329         (mapc #'notmuch-address-harvest-addr
330               (apply 'notmuch-call-notmuch-sexp args))
331       ;; Asynchronous
332       (let* ((current-proc (if addr-prefix
333                                (car notmuch-address-harvest-procs)
334                              (cdr notmuch-address-harvest-procs)))
335              (proc-name (format "notmuch-address-%s-harvest"
336                                 (if addr-prefix "partial" "full")))
337              (proc-buf (concat " *" proc-name "*")))
338         ;; Kill any existing process
339         (when current-proc
340           (kill-buffer (process-buffer current-proc))) ; this also kills the process
341         (setq current-proc
342               (apply 'notmuch-start-notmuch proc-name proc-buf
343                      callback                           ; process sentinel
344                      args))
345         (set-process-filter current-proc 'notmuch-address-harvest-filter)
346         (set-process-query-on-exit-flag current-proc nil)
347         (if addr-prefix
348             (setcar notmuch-address-harvest-procs current-proc)
349           (setcdr notmuch-address-harvest-procs current-proc)))))
350   ;; return value
351   nil)
352
353 (defvar notmuch-address--save-hash-version 1
354   "Version format of the save hash.")
355
356 (defun notmuch-address--get-address-hash ()
357   "Return the saved address hash as a plist.
358
359 Returns nil if the save file does not exist, or it does not seem
360 to be a saved address hash."
361   (and notmuch-address-save-filename
362        (condition-case nil
363            (with-temp-buffer
364              (insert-file-contents notmuch-address-save-filename)
365              (let ((name (read (current-buffer)))
366                    (plist (read (current-buffer))))
367                ;; We do two simple sanity checks on the loaded file.
368                ;; We just check a version is specified, not that
369                ;; it is the current version, as we are allowed to
370                ;; over-write and a save-file with an older version.
371                (and (string= name "notmuch-address-hash")
372                     (plist-get plist :version)
373                     plist)))
374          ;; The error case catches any of the reads failing.
375          (error nil))))
376
377 (defun notmuch-address--load-address-hash ()
378   "Read the saved address hash and set the corresponding variables."
379   (let ((load-plist (notmuch-address--get-address-hash)))
380     (when (and load-plist
381                ;; If the user's setting have changed, or the version
382                ;; has changed, return nil to make sure the new settings
383                ;; take effect.
384                (equal (plist-get load-plist :completion-settings)
385                       notmuch-address-internal-completion)
386                (equal (plist-get load-plist :version)
387                       notmuch-address--save-hash-version))
388       (setq notmuch-address-last-harvest (plist-get load-plist :last-harvest))
389       (setq notmuch-address-completions (plist-get load-plist :completions))
390       (setq notmuch-address-full-harvest-finished t)
391       ;; Return t to say load was successful.
392       t)))
393
394 (defun notmuch-address--save-address-hash ()
395   (when notmuch-address-save-filename
396     (if (or (not (file-exists-p notmuch-address-save-filename))
397             ;; The file exists, check it is a file we saved
398             (notmuch-address--get-address-hash))
399         (with-temp-file notmuch-address-save-filename
400           (let ((save-plist
401                  (list :version notmuch-address--save-hash-version
402                        :completion-settings notmuch-address-internal-completion
403                        :last-harvest notmuch-address-last-harvest
404                        :completions notmuch-address-completions)))
405             (print "notmuch-address-hash" (current-buffer))
406             (print save-plist (current-buffer))))
407       (message "\
408 Warning: notmuch-address-save-filename %s exists but doesn't
409 appear to be an address savefile.  Not overwriting."
410                notmuch-address-save-filename))))
411
412 (defun notmuch-address-harvest-trigger ()
413   (let ((now (float-time)))
414     (when (> (- now notmuch-address-last-harvest) 86400)
415       (setq notmuch-address-last-harvest now)
416       (notmuch-address-harvest
417        nil nil
418        (lambda (proc event)
419          ;; If harvest fails, we want to try
420          ;; again when the trigger is next
421          ;; called
422          (if (string= event "finished\n")
423              (progn
424                (notmuch-address--save-address-hash)
425                (setq notmuch-address-full-harvest-finished t))
426            (setq notmuch-address-last-harvest 0)))))))
427
428 ;;
429
430 (defun notmuch-address-from-minibuffer (prompt)
431   (if (not notmuch-address-command)
432       (read-string prompt)
433     (let ((rmap (copy-keymap minibuffer-local-map))
434           (omap minibuffer-local-map))
435       ;; Configure TAB to start completion when executing read-string.
436       ;; "Original" minibuffer keymap is restored just before calling
437       ;; notmuch-address-expand-name as it may also use minibuffer-local-map
438       ;; (completing-read probably does not but if something else is used there).
439       (define-key rmap (kbd "TAB") (lambda ()
440                                      (interactive)
441                                      (let ((enable-recursive-minibuffers t)
442                                            (minibuffer-local-map omap))
443                                        (notmuch-address-expand-name))))
444       (let ((minibuffer-local-map rmap))
445         (read-string prompt)))))
446
447 ;;
448
449 (provide 'notmuch-address)
450
451 ;;; notmuch-address.el ends here