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