]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-address.el
Merge branch 'release'
[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 <http://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: David Edmondson <dme@dme.org>
21
22 (require 'message)
23 (require 'notmuch-parser)
24 (require 'notmuch-lib)
25 (require 'notmuch-company)
26 ;;
27 (declare-function company-manual-begin "company")
28
29 (defcustom notmuch-address-command 'internal
30   "The command which generates possible addresses. It must take a
31 single argument and output a list of possible matches, one per
32 line. The default value of `internal' uses built-in address
33 completion."
34   :type '(radio
35           (const :tag "Use internal address completion" internal)
36           (const :tag "Disable address completion" nil)
37           (string :tag "Use external completion command" "notmuch-addresses"))
38   :group 'notmuch-send
39   :group 'notmuch-external)
40
41 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
42   "The function to select address from given list. The function is
43 called with PROMPT, COLLECTION, and INITIAL-INPUT as arguments
44 (subset of what `completing-read' can be called with).
45 While executed the value of `completion-ignore-case' is t.
46 See documentation of function `notmuch-address-selection-function'
47 to know how address selection is made by default."
48   :type 'function
49   :group 'notmuch-send
50   :group 'notmuch-external)
51
52 (defvar notmuch-address-last-harvest 0
53   "Time of last address harvest")
54
55 (defvar notmuch-address-completions (make-hash-table :test 'equal)
56   "Hash of email addresses for completion during email composition.
57   This variable is set by calling `notmuch-address-harvest'.")
58
59 (defvar notmuch-address-full-harvest-finished nil
60   "t indicates that full completion address harvesting has been
61 finished")
62
63 (defun notmuch-address-selection-function (prompt collection initial-input)
64   "Call (`completing-read'
65       PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
66   (completing-read
67    prompt collection nil nil initial-input 'notmuch-address-history))
68
69 (defvar notmuch-address-completion-headers-regexp
70   "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
71
72 (defvar notmuch-address-history nil)
73
74 (defun notmuch-address-message-insinuate ()
75   (message "calling notmuch-address-message-insinuate is no longer needed"))
76
77 (defcustom notmuch-address-use-company t
78   "If available, use company mode for address completion"
79   :type 'boolean
80   :group 'notmuch-send)
81
82 (defun notmuch-address-setup ()
83   (let* ((use-company (and notmuch-address-use-company
84                            (eq notmuch-address-command 'internal)
85                            (require 'company nil t)))
86          (pair (cons notmuch-address-completion-headers-regexp
87                      (if use-company
88                          #'company-manual-begin
89                        #'notmuch-address-expand-name))))
90       (when use-company
91         (notmuch-company-setup))
92       (unless (memq pair message-completion-alist)
93         (setq message-completion-alist
94               (push pair message-completion-alist)))))
95
96 (defun notmuch-address-matching (substring)
97   "Returns a list of completion candidates matching SUBSTRING.
98 The candidates are taken from `notmuch-address-completions'."
99   (let ((candidates)
100         (re (regexp-quote substring)))
101     (maphash (lambda (key val)
102                (when (string-match re key)
103                  (push key candidates)))
104              notmuch-address-completions)
105     candidates))
106
107 (defun notmuch-address-options (original)
108   "Returns a list of completion candidates. Uses either
109 elisp-based implementation or older implementation requiring
110 external commands."
111   (cond
112    ((eq notmuch-address-command 'internal)
113     (when (not notmuch-address-full-harvest-finished)
114       ;; First, run quick synchronous harvest based on what the user
115       ;; entered so far
116       (notmuch-address-harvest (format "to:%s*" original) t))
117     (prog1 (notmuch-address-matching original)
118       ;; Then start the (potentially long-running) full asynchronous harvest if necessary
119       (notmuch-address-harvest-trigger)))
120    (t
121     (process-lines notmuch-address-command original))))
122
123 (defun notmuch-address-expand-name ()
124   (when notmuch-address-command
125     (let* ((end (point))
126            (beg (save-excursion
127                   (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
128                   (goto-char (match-end 0))
129                   (point)))
130            (orig (buffer-substring-no-properties beg end))
131            (completion-ignore-case t)
132            (options (with-temp-message "Looking for completion candidates..."
133                       (notmuch-address-options orig)))
134            (num-options (length options))
135            (chosen (cond
136                     ((eq num-options 0)
137                      nil)
138                     ((eq num-options 1)
139                      (car options))
140                     (t
141                      (funcall notmuch-address-selection-function
142                               (format "Address (%s matches): " num-options)
143                               (cdr options) (car options))))))
144       (if chosen
145           (progn
146             (push chosen notmuch-address-history)
147             (delete-region beg end)
148             (insert chosen))
149         (message "No matches.")
150         (ding)))))
151
152 ;; Copied from `w3m-which-command'.
153 (defun notmuch-address-locate-command (command)
154   "Return non-nil if `command' is an executable either on
155 `exec-path' or an absolute pathname."
156   (when (stringp command)
157     (if (and (file-name-absolute-p command)
158              (file-executable-p command))
159         command
160       (setq command (file-name-nondirectory command))
161       (catch 'found-command
162         (let (bin)
163           (dolist (dir exec-path)
164             (setq bin (expand-file-name command dir))
165             (when (or (and (file-executable-p bin)
166                            (not (file-directory-p bin)))
167                       (and (file-executable-p (setq bin (concat bin ".exe")))
168                            (not (file-directory-p bin))))
169               (throw 'found-command bin))))))))
170
171 (defun notmuch-address-harvest-addr (result)
172   (let ((name-addr (plist-get result :name-addr)))
173     (puthash name-addr t notmuch-address-completions)))
174
175 (defun notmuch-address-harvest-handle-result (obj)
176   (notmuch-address-harvest-addr obj))
177
178 (defun notmuch-address-harvest-filter (proc string)
179   (when (buffer-live-p (process-buffer proc))
180     (with-current-buffer (process-buffer proc)
181       (save-excursion
182         (goto-char (point-max))
183         (insert string))
184       (notmuch-sexp-parse-partial-list
185        'notmuch-address-harvest-handle-result (process-buffer proc)))))
186
187 (defvar notmuch-address-harvest-procs '(nil . nil)
188   "The currently running harvests.
189
190 The car is a partial harvest, and the cdr is a full harvest")
191
192 (defun notmuch-address-harvest (&optional filter-query synchronous callback)
193   "Collect addresses completion candidates. It queries the
194 notmuch database for all messages sent by the user optionally
195 matching FILTER-QUERY (if not nil). It collects the destination
196 addresses from those messages and stores them in
197 `notmuch-address-completions'. Address harvesting may take some
198 time so the address collection runs asynchronously unless
199 SYNCHRONOUS is t. In case of asynchronous execution, CALLBACK is
200 called when harvesting finishes."
201   (let* ((from-me-query (mapconcat (lambda (x) (concat "from:" x)) (notmuch-user-emails) " or "))
202          (query (if filter-query
203                     (format "(%s) and (%s)" from-me-query filter-query)
204                   from-me-query))
205          (args `("address" "--format=sexp" "--format-version=2"
206                  "--output=recipients"
207                  "--deduplicate=address"
208                  ,query)))
209     (if synchronous
210         (mapc #'notmuch-address-harvest-addr
211                                    (apply 'notmuch-call-notmuch-sexp args))
212       ;; Asynchronous
213       (let* ((current-proc (if filter-query
214                                (car notmuch-address-harvest-procs)
215                              (cdr notmuch-address-harvest-procs)))
216              (proc-name (format "notmuch-address-%s-harvest"
217                                 (if filter-query "partial" "full")))
218              (proc-buf (concat " *" proc-name "*")))
219         ;; Kill any existing process
220         (when current-proc
221           (kill-buffer (process-buffer current-proc))) ; this also kills the process
222
223         (setq current-proc
224               (apply 'notmuch-start-notmuch proc-name proc-buf
225                      callback                           ; process sentinel
226                      args))
227         (set-process-filter current-proc 'notmuch-address-harvest-filter)
228         (set-process-query-on-exit-flag current-proc nil)
229         (if filter-query
230             (setcar notmuch-address-harvest-procs current-proc)
231           (setcdr notmuch-address-harvest-procs current-proc)))))
232   ;; return value
233   nil)
234
235 (defun notmuch-address-harvest-trigger ()
236   (let ((now (float-time)))
237     (when (> (- now notmuch-address-last-harvest) 86400)
238       (setq notmuch-address-last-harvest now)
239       (notmuch-address-harvest nil nil
240                                (lambda (proc event)
241                                  ;; If harvest fails, we want to try
242                                  ;; again when the trigger is next
243                                  ;; called
244                                  (if (string= event "finished\n")
245                                      (setq notmuch-address-full-harvest-finished t)
246                                    (setq notmuch-address-last-harvest 0)))))))
247
248 ;;
249
250 (provide 'notmuch-address)