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