]> rtime.felk.cvut.cz Git - notmuch.git/blob - emacs/notmuch-address.el
emacs: address completion, allow sender/recipient and filters
[notmuch.git] / 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 <http://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")
41
42 (defcustom notmuch-address-command '(sent nil)
43   "Determines how to generate address completion candidates.
44
45 If it is a string then that string should be an external program
46 which must take a single argument (searched string) and output a
47 list of completion candidates, one per line.
48
49 Alternatively, it can be a (non-nil) list, in which case internal
50 completion is used; in this case the list should have form
51 '(DIRECTION FILTER), where DIRECTION is either sent or received
52 and specifies whether the candidates are searched in messages
53 sent by the user or received by the user (note received by is
54 much faster), and FILTER is either nil or a filter-string, such
55 as \"date:1y..\" to append to the query.
56
57 If this variable is nil then address completion is disabled."
58   :type '(radio
59           (list :tag "Use internal address completion"
60                 (radio
61                  :tag "Base completion on messages you have"
62                  :value sent
63                  (const :tag "sent (more accurate)" sent)
64                  (const :tag "received (faster)" received))
65                 (radio :tag "Filter messages used for completion"
66                        (const :tag "Use all messages" nil)
67                        (string :tag "Filter query")))
68           (const :tag "Disable address completion" nil)
69           (string :tag "Use external completion command"))
70   ;; We override set so that we can clear the cache when this changes
71   :set (lambda (symbol value)
72          (set-default symbol value)
73          (setq notmuch-address-last-harvest 0)
74          (setq notmuch-address-completions (clrhash notmuch-address-completions))
75          (setq notmuch-address-full-harvest-finished nil))
76   :group 'notmuch-send
77   :group 'notmuch-external)
78
79 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
80   "The function to select address from given list. The function is
81 called with PROMPT, COLLECTION, and INITIAL-INPUT as arguments
82 (subset of what `completing-read' can be called with).
83 While executed the value of `completion-ignore-case' is t.
84 See documentation of function `notmuch-address-selection-function'
85 to know how address selection is made by default."
86   :type 'function
87   :group 'notmuch-send
88   :group 'notmuch-external)
89
90 (defun notmuch-address-selection-function (prompt collection initial-input)
91   "Call (`completing-read'
92       PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
93   (completing-read
94    prompt collection nil nil initial-input 'notmuch-address-history))
95
96 (defvar notmuch-address-completion-headers-regexp
97   "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
98
99 (defvar notmuch-address-history nil)
100
101 (defun notmuch-address-message-insinuate ()
102   (message "calling notmuch-address-message-insinuate is no longer needed"))
103
104 (defcustom notmuch-address-use-company t
105   "If available, use company mode for address completion"
106   :type 'boolean
107   :group 'notmuch-send)
108
109 (defun notmuch-address-setup ()
110   (let* ((use-company (and notmuch-address-use-company
111                            notmuch-address-command
112                            (listp notmuch-address-command)
113                            (require 'company nil t)))
114          (pair (cons notmuch-address-completion-headers-regexp
115                      (if use-company
116                          #'company-manual-begin
117                        #'notmuch-address-expand-name))))
118       (when use-company
119         (notmuch-company-setup))
120       (unless (memq pair message-completion-alist)
121         (setq message-completion-alist
122               (push pair message-completion-alist)))))
123
124 (defun notmuch-address-matching (substring)
125   "Returns a list of completion candidates matching SUBSTRING.
126 The candidates are taken from `notmuch-address-completions'."
127   (let ((candidates)
128         (re (regexp-quote substring)))
129     (maphash (lambda (key val)
130                (when (string-match re key)
131                  (push key candidates)))
132              notmuch-address-completions)
133     candidates))
134
135 (defun notmuch-address-options (original)
136   "Returns a list of completion candidates. Uses either
137 elisp-based implementation or older implementation requiring
138 external commands."
139   (cond
140    ((and notmuch-address-command (listp notmuch-address-command))
141     (when (not notmuch-address-full-harvest-finished)
142       ;; First, run quick synchronous harvest based on what the user
143       ;; entered so far
144       (notmuch-address-harvest original t))
145     (prog1 (notmuch-address-matching original)
146       ;; Then start the (potentially long-running) full asynchronous harvest if necessary
147       (notmuch-address-harvest-trigger)))
148    (t
149     (process-lines notmuch-address-command original))))
150
151 (defun notmuch-address-expand-name ()
152   (when notmuch-address-command
153     (let* ((end (point))
154            (beg (save-excursion
155                   (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
156                   (goto-char (match-end 0))
157                   (point)))
158            (orig (buffer-substring-no-properties beg end))
159            (completion-ignore-case t)
160            (options (with-temp-message "Looking for completion candidates..."
161                       (notmuch-address-options orig)))
162            (num-options (length options))
163            (chosen (cond
164                     ((eq num-options 0)
165                      nil)
166                     ((eq num-options 1)
167                      (car options))
168                     (t
169                      (funcall notmuch-address-selection-function
170                               (format "Address (%s matches): " num-options)
171                               (cdr options) (car options))))))
172       (if chosen
173           (progn
174             (push chosen notmuch-address-history)
175             (delete-region beg end)
176             (insert chosen))
177         (message "No matches.")
178         (ding)))))
179
180 ;; Copied from `w3m-which-command'.
181 (defun notmuch-address-locate-command (command)
182   "Return non-nil if `command' is an executable either on
183 `exec-path' or an absolute pathname."
184   (when (stringp command)
185     (if (and (file-name-absolute-p command)
186              (file-executable-p command))
187         command
188       (setq command (file-name-nondirectory command))
189       (catch 'found-command
190         (let (bin)
191           (dolist (dir exec-path)
192             (setq bin (expand-file-name command dir))
193             (when (or (and (file-executable-p bin)
194                            (not (file-directory-p bin)))
195                       (and (file-executable-p (setq bin (concat bin ".exe")))
196                            (not (file-directory-p bin))))
197               (throw 'found-command bin))))))))
198
199 (defun notmuch-address-harvest-addr (result)
200   (let ((name-addr (plist-get result :name-addr)))
201     (puthash name-addr t notmuch-address-completions)))
202
203 (defun notmuch-address-harvest-handle-result (obj)
204   (notmuch-address-harvest-addr obj))
205
206 (defun notmuch-address-harvest-filter (proc string)
207   (when (buffer-live-p (process-buffer proc))
208     (with-current-buffer (process-buffer proc)
209       (save-excursion
210         (goto-char (point-max))
211         (insert string))
212       (notmuch-sexp-parse-partial-list
213        'notmuch-address-harvest-handle-result (process-buffer proc)))))
214
215 (defvar notmuch-address-harvest-procs '(nil . nil)
216   "The currently running harvests.
217
218 The car is a partial harvest, and the cdr is a full harvest")
219
220 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
221   "Collect addresses completion candidates.
222
223 It queries the notmuch database for messages sent/received (as
224 configured with `notmuch-address-command`) by the user, collects
225 destination/source addresses from those messages and stores them
226 in `notmuch-address-completions'.
227
228 If ADDR-PREFIX is not nil, only messages with to/from addresses
229 matching ADDR-PREFIX*' are queried.
230
231 Address harvesting may take some time so the address collection runs
232 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
233 execution, CALLBACK is called when harvesting finishes."
234
235   (let* ((sent (eq (car notmuch-address-command) 'sent))
236          (config-query (cadr notmuch-address-command))
237          (prefix-query (when addr-prefix
238                          (format "%s:%s*" (if sent "to" "from") addr-prefix)))
239          (from-or-to-me-query
240           (mapconcat (lambda (x)
241                        (concat (if sent "from:" "to:") x))
242                      (notmuch-user-emails) " or "))
243          (query (if (or prefix-query config-query)
244                     (concat (format "(%s)" from-or-to-me-query)
245                             (when prefix-query
246                               (format " and (%s)" prefix-query))
247                             (when config-query
248                               (format " and (%s)" config-query)))
249                   from-or-to-me-query))
250          (args `("address" "--format=sexp" "--format-version=2"
251                  ,(if sent "--output=recipients" "--output=sender")
252                  "--deduplicate=address"
253                  ,query)))
254     (if synchronous
255         (mapc #'notmuch-address-harvest-addr
256                                    (apply 'notmuch-call-notmuch-sexp args))
257       ;; Asynchronous
258       (let* ((current-proc (if addr-prefix
259                                (car notmuch-address-harvest-procs)
260                              (cdr notmuch-address-harvest-procs)))
261              (proc-name (format "notmuch-address-%s-harvest"
262                                 (if addr-prefix "partial" "full")))
263              (proc-buf (concat " *" proc-name "*")))
264         ;; Kill any existing process
265         (when current-proc
266           (kill-buffer (process-buffer current-proc))) ; this also kills the process
267
268         (setq current-proc
269               (apply 'notmuch-start-notmuch proc-name proc-buf
270                      callback                           ; process sentinel
271                      args))
272         (set-process-filter current-proc 'notmuch-address-harvest-filter)
273         (set-process-query-on-exit-flag current-proc nil)
274         (if addr-prefix
275             (setcar notmuch-address-harvest-procs current-proc)
276           (setcdr notmuch-address-harvest-procs current-proc)))))
277   ;; return value
278   nil)
279
280 (defun notmuch-address-harvest-trigger ()
281   (let ((now (float-time)))
282     (when (> (- now notmuch-address-last-harvest) 86400)
283       (setq notmuch-address-last-harvest now)
284       (notmuch-address-harvest nil nil
285                                (lambda (proc event)
286                                  ;; If harvest fails, we want to try
287                                  ;; again when the trigger is next
288                                  ;; called
289                                  (if (string= event "finished\n")
290                                      (setq notmuch-address-full-harvest-finished t)
291                                    (setq notmuch-address-last-harvest 0)))))))
292
293 ;;
294
295 (provide 'notmuch-address)
296
297 ;;; notmuch-address.el ends here