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