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