]> code.delx.au - gnu-emacs-elpa/blob - async.el
Merge branch 'master' of github.com:jwiegley/emacs-async
[gnu-emacs-elpa] / async.el
1 ;;; async --- Asynchronous processing in Emacs
2
3 ;; Copyright (C) 2012 John Wiegley
4
5 ;; Author: John Wiegley <jwiegley@gmail.com>
6 ;; Created: 18 Jun 2012
7 ;; Version: 1.1
8 ;; Keywords: async
9 ;; X-URL: https://github.com/jwiegley/emacs-async
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25 \f
26 ;;; Commentary:
27
28 ;; Adds the ability to call asynchronous functions and process with ease. See
29 ;; the documentation for `async-start' and `async-start-process'.
30 \f
31 ;;; Code:
32
33 (defgroup async nil
34 "Simple asynchronous processing in Emacs"
35 :group 'emacs)
36
37 (defvar async-debug nil)
38 (defvar async-send-over-pipe t)
39 (defvar async-in-child-emacs nil)
40 (defvar async-callback nil)
41 (defvar async-callback-for-process nil)
42 (defvar async-callback-value nil)
43 (defvar async-callback-value-set nil)
44 (defvar async-current-process nil)
45
46 (defun async-inject-variables
47 (include-regexp &optional predicate exclude-regexp)
48 "Return a `setq' form that replicates part of the calling environment.
49 It sets the value for every variable matching INCLUDE-REGEXP and
50 also PREDICATE. It will not perform injection for any variable
51 matching EXCLUDE-REGEXP (if present). It is intended to be used
52 as follows:
53
54 (async-start
55 `(lambda ()
56 (require 'smtpmail)
57 (with-temp-buffer
58 (insert ,(buffer-substring-no-properties (point-min) (point-max)))
59 ;; Pass in the variable environment for smtpmail
60 ,(async-inject-variables \"\\`\\(smtpmail\\|\\(user-\\)?mail\\)-\")
61 (smtpmail-send-it)))
62 'ignore)"
63 `(setq
64 ,@(let (bindings)
65 (mapatoms
66 (lambda (sym)
67 (if (and (boundp sym)
68 (or (null include-regexp)
69 (string-match include-regexp (symbol-name sym)))
70 (not (string-match
71 (or exclude-regexp "-syntax-table\\'")
72 (symbol-name sym))))
73 (let ((value (symbol-value sym)))
74 (when (or (null predicate)
75 (funcall predicate sym))
76 (setq bindings (cons `(quote ,value) bindings)
77 bindings (cons sym bindings)))))))
78 bindings)))
79
80 (defalias 'async-inject-environment 'async-inject-variables)
81
82 (defun async-handle-result (func result buf)
83 (if (null func)
84 (progn
85 (set (make-local-variable 'async-callback-value) result)
86 (set (make-local-variable 'async-callback-value-set) t))
87 (unwind-protect
88 (if (and (listp result)
89 (eq 'async-signal (nth 0 result)))
90 (signal (car (nth 1 result))
91 (cdr (nth 1 result)))
92 (funcall func result))
93 (unless async-debug
94 (kill-buffer buf)))))
95
96 (defun async-when-done (proc &optional change)
97 "Process sentinal used to retrieve the value from the child process."
98 (when (eq 'exit (process-status proc))
99 (with-current-buffer (process-buffer proc)
100 (let ((async-current-process proc))
101 (if (= 0 (process-exit-status proc))
102 (if async-callback-for-process
103 (if async-callback
104 (prog1
105 (funcall async-callback proc)
106 (unless async-debug
107 (kill-buffer (current-buffer))))
108 (set (make-local-variable 'async-callback-value) proc)
109 (set (make-local-variable 'async-callback-value-set) t))
110 (goto-char (point-max))
111 (backward-sexp)
112 (async-handle-result async-callback (read (current-buffer))
113 (current-buffer)))
114 (set (make-local-variable 'async-callback-value)
115 (list 'error
116 (format "Async process '%s' failed with exit code %d"
117 (process-name proc) (process-exit-status proc))))
118 (set (make-local-variable 'async-callback-value-set) t))))))
119
120 (defun async--receive-sexp (&optional stream)
121 (let ((sexp (base64-decode-string (read stream))))
122 (if async-debug
123 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
124 (setq sexp (read sexp))
125 (if async-debug
126 (message "Read sexp {{{%s}}}" (pp-to-string sexp)))
127 (eval sexp)))
128
129 (defun async--insert-sexp (sexp)
130 (prin1 sexp (current-buffer))
131 ;; Just in case the string we're sending might contain EOF
132 (base64-encode-region (point-min) (point-max) t)
133 (goto-char (point-min)) (insert ?\")
134 (goto-char (point-max)) (insert ?\" ?\n))
135
136 (defun async--transmit-sexp (process sexp)
137 (with-temp-buffer
138 (if async-debug
139 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
140 (async--insert-sexp sexp)
141 (process-send-region process (point-min) (point-max))))
142
143 (defun async-batch-invoke ()
144 "Called from the child Emacs process' command-line."
145 (setq async-in-child-emacs t
146 debug-on-error async-debug)
147 (if debug-on-error
148 (prin1 (funcall
149 (async--receive-sexp (unless async-send-over-pipe
150 command-line-args-left))))
151 (condition-case err
152 (prin1 (funcall
153 (async--receive-sexp (unless async-send-over-pipe
154 command-line-args-left))))
155 (error
156 (prin1 (list 'async-signal err))))))
157
158 (defun async-ready (future)
159 "Query a FUTURE to see if the ready is ready -- i.e., if no blocking
160 would result from a call to `async-get' on that FUTURE."
161 (and (memq (process-status future) '(exit signal))
162 (with-current-buffer (process-buffer future)
163 async-callback-value-set)))
164
165 (defun async-wait (future)
166 "Wait for FUTURE to become ready."
167 (while (not (async-ready future))
168 (sit-for 0.05)))
169
170 (defun async-get (future)
171 "Get the value from an asynchronously function when it is ready.
172 FUTURE is returned by `async-start' or `async-start-process' when
173 its FINISH-FUNC is nil."
174 (async-wait future)
175 (with-current-buffer (process-buffer future)
176 (async-handle-result #'identity async-callback-value (current-buffer))))
177
178 (defun async-message-p (value)
179 "Return true of VALUE is an async.el message packet."
180 (and (listp value)
181 (plist-get value :async-message)))
182
183 (defun async-send (&rest args)
184 "Send the given messages to the asychronous Emacs PROCESS."
185 (let ((args (append args '(:async-message t))))
186 (if async-in-child-emacs
187 (if async-callback
188 (funcall async-callback args))
189 (async--transmit-sexp (car args) (list 'quote (cdr args))))))
190
191 (defun async-receive (&rest args)
192 "Send the given messages to the asychronous Emacs PROCESS."
193 (async--receive-sexp))
194
195 ;;;###autoload
196 (defun async-start-process (name program finish-func &rest program-args)
197 "Start the executable PROGRAM asynchronously. See `async-start'.
198 PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the
199 process object when done. If FINISH-FUNC is nil, the future
200 object will return the process object when the program is
201 finished."
202 (let* ((buf (generate-new-buffer (concat "*" name "*")))
203 (proc (let ((process-connection-type nil))
204 (apply #'start-process name buf program program-args))))
205 (with-current-buffer buf
206 (set (make-local-variable 'async-callback) finish-func)
207 (set-process-sentinel proc #'async-when-done)
208 (unless (string= name "emacs")
209 (set (make-local-variable 'async-callback-for-process) t))
210 proc)))
211
212 ;;;###autoload
213 (defmacro async-start (start-func &optional finish-func)
214 "Execute START-FUNC (often a lambda) in a subordinate Emacs process.
215 When done, the return value is passed to FINISH-FUNC. Example:
216
217 (async-start
218 ;; What to do in the child process
219 (lambda ()
220 (message \"This is a test\")
221 (sleep-for 3)
222 222)
223
224 ;; What to do when it finishes
225 (lambda (result)
226 (message \"Async process done, result should be 222: %s\"
227 result)))
228
229 If FINISH-FUNC is nil or missing, a future is returned that can
230 be inspected using `async-get', blocking until the value is
231 ready. Example:
232
233 (let ((proc (async-start
234 ;; What to do in the child process
235 (lambda ()
236 (message \"This is a test\")
237 (sleep-for 3)
238 222))))
239
240 (message \"I'm going to do some work here\") ;; ....
241
242 (message \"Waiting on async process, result should be 222: %s\"
243 (async-get proc)))
244
245 If you don't want to use a callback, and you don't care about any
246 return value form the child process, pass the `ignore' symbol as
247 the second argument (if you don't, and never call `async-get', it
248 will leave *emacs* process buffers hanging around):
249
250 (async-start
251 (lambda ()
252 (delete-file \"a remote file on a slow link\" nil))
253 'ignore)
254
255 Note: Even when FINISH-FUNC is present, a future is still
256 returned except that it yields no value (since the value is
257 passed to FINISH-FUNC). Call `async-get' on such a future always
258 returns nil. It can still be useful, however, as an argument to
259 `async-ready' or `async-wait'."
260 (require 'find-func)
261 (let ((procvar (make-symbol "proc")))
262 `(let* ((sexp ,start-func)
263 (,procvar
264 (async-start-process
265 "emacs" (file-truename
266 (expand-file-name invocation-name
267 invocation-directory))
268 ,finish-func
269 "-Q" "-l" ,(funcall (symbol-function 'find-library-name)
270 "async")
271 "-batch" "-f" "async-batch-invoke"
272 (if async-send-over-pipe
273 "<none>"
274 (with-temp-buffer
275 (async--insert-sexp (list 'quote sexp))
276 (buffer-string))))))
277 (if async-send-over-pipe
278 (async--transmit-sexp ,procvar (list 'quote sexp)))
279 ,procvar)))
280
281 (defmacro async-sandbox(func)
282 "Evaluate FUNC in a separate Emacs process, synchronously."
283 `(async-get (async-start ,func)))
284
285 (provide 'async)
286
287 ;;; async.el ends here