]> code.delx.au - gnu-emacs-elpa/blob - async.el
Some minor adjustments
[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 nil)
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-when-done (proc &optional change)
83 "Process sentinal used to retrieve the value from the child process."
84 (when (eq 'exit (process-status proc))
85 (with-current-buffer (process-buffer proc)
86 (let ((async-current-process proc))
87 (if (= 0 (process-exit-status proc))
88 (if async-callback-for-process
89 (if async-callback
90 (prog1
91 (funcall async-callback proc)
92 (unless async-debug
93 (kill-buffer (current-buffer))))
94 (set (make-local-variable 'async-callback-value) proc)
95 (set (make-local-variable 'async-callback-value-set) t))
96 (goto-char (point-max))
97 (backward-sexp)
98 (let ((result (read (current-buffer))))
99 (if (and (listp result)
100 (eq 'async-signal (car result)))
101 (if (eq 'error (car (cdr result)))
102 (error (cadr (cdr result)))
103 (signal (cadr result)
104 (cddr result)))
105 (if async-callback
106 (prog1
107 (funcall async-callback result)
108 (unless async-debug
109 (kill-buffer (current-buffer))))
110 (set (make-local-variable 'async-callback-value) result)
111 (set (make-local-variable 'async-callback-value-set) t)))))
112 (set (make-local-variable 'async-callback-value) 'error)
113 (set (make-local-variable 'async-callback-value-set) t)
114 (error "Async process '%s' failed with exit code %d"
115 (process-name proc) (process-exit-status proc)))))))
116
117 (defun async--receive-sexp (&optional stream)
118 (let ((sexp (if async-send-over-pipe
119 (read (base64-decode-string (read stream)))
120 (read stream))))
121 (if async-debug
122 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
123 (eval sexp)))
124
125 (defun async--insert-sexp (sexp)
126 (if async-send-over-pipe
127 (progn
128 (prin1 sexp (current-buffer))
129 ;; Just in case the string we're sending might contain EOF
130 (base64-encode-region (point-min) (point-max) t)
131 (goto-char (point-min)) (insert ?\")
132 (goto-char (point-max)) (insert ?\" ?\n))
133 (let ((print-escape-newlines t))
134 (prin1 (list 'quote ,start-func) (current-buffer)))
135 (insert ?\n)))
136
137 (defun async--transmit-sexp (process sexp)
138 (with-temp-buffer
139 (if async-debug
140 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
141 (async--insert-sexp sexp)
142 (process-send-region process (point-min) (point-max))))
143
144 (defun async-batch-invoke ()
145 "Called from the child Emacs process' command-line."
146 (setq async-in-child-emacs t)
147 (condition-case err
148 (prin1 (funcall
149 (async--receive-sexp (unless async-send-over-pipe
150 command-line-args-left))))
151 (error
152 (backtrace)
153 (prin1 `(async-signal . ,err)))))
154
155 (defun async-ready (future)
156 "Query a FUTURE to see if the ready is ready -- i.e., if no blocking
157 would result from a call to `async-get' on that FUTURE."
158 (and (eq 'exit (process-status future))
159 async-callback-value-set))
160
161 (defun async-wait (future)
162 "Wait for FUTURE to become ready."
163 (while (not (async-ready future))
164 (sit-for 0.05)))
165
166 (defun async-get (future)
167 "Get the value from an asynchronously function when it is ready.
168 FUTURE is returned by `async-start' or `async-start-process' when
169 its FINISH-FUNC is nil."
170 (async-wait future)
171 (with-current-buffer (process-buffer future)
172 (prog1
173 async-callback-value
174 (kill-buffer (current-buffer)))))
175
176 ;;;###autoload
177 (defun async-start-process (name program finish-func &rest program-args)
178 "Start the executable PROGRAM asynchronously. See `async-start'.
179 PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the
180 process object when done. If FINISH-FUNC is nil, the future
181 object will return the process object when the program is
182 finished."
183 (let* ((buf (generate-new-buffer (concat "*" name "*")))
184 (proc (apply #'start-process name buf program program-args)))
185 (with-current-buffer buf
186 (set (make-local-variable 'async-callback) finish-func)
187 (set-process-sentinel proc #'async-when-done)
188 (unless (string= name "emacs")
189 (set (make-local-variable 'async-callback-for-process) t))
190 proc)))
191
192 ;;;###autoload
193 (defmacro async-start (start-func &optional finish-func)
194 "Execute START-FUNC (often a lambda) in a subordinate Emacs process.
195 When done, the return value is passed to FINISH-FUNC. Example:
196
197 (async-start
198 ;; What to do in the child process
199 (lambda ()
200 (message \"This is a test\")
201 (sleep-for 3)
202 222)
203
204 ;; What to do when it finishes
205 (lambda (result)
206 (message \"Async process done, result should be 222: %s\"
207 result)))
208
209 If FINISH-FUNC is nil or missing, a future is returned that can
210 be inspected using `async-get', blocking until the value is
211 ready. Example:
212
213 (let ((proc (async-start
214 ;; What to do in the child process
215 (lambda ()
216 (message \"This is a test\")
217 (sleep-for 3)
218 222))))
219
220 (message \"I'm going to do some work here\") ;; ....
221
222 (message \"Waiting on async process, result should be 222: %s\"
223 (async-get proc)))
224
225 If you don't want to use a callback, and you don't care about any
226 return value form the child process, pass the `ignore' symbol as
227 the second argument (if you don't, and never call `async-get', it
228 will leave *emacs* process buffers hanging around):
229
230 (async-start
231 (lambda ()
232 (delete-file \"a remote file on a slow link\" nil))
233 'ignore)
234
235 Note: Even when FINISH-FUNC is present, a future is still
236 returned except that it yields no value (since the value is
237 passed to FINISH-FUNC). Call `async-get' on such a future always
238 returns nil. It can still be useful, however, as an argument to
239 `async-ready' or `async-wait'."
240 (require 'find-func)
241 (let ((procvar (make-symbol "proc")))
242 `(let* ((sexp ,start-func)
243 (,procvar
244 (async-start-process
245 "emacs" (expand-file-name invocation-name
246 invocation-directory)
247 ,finish-func
248 "-Q" "-l" ,(find-library-name "async")
249 "-batch" "-f" "async-batch-invoke"
250 ,(and async-send-over-pipe
251 '(with-temp-buffer
252 (async--insert-sexp (list 'quote sexp))
253 (buffer-string))))))
254 ,(if async-send-over-pipe
255 `(async--transmit-sexp ,procvar (list 'quote sexp)))
256 ,procvar)))
257
258 (defun async-test-1 ()
259 (interactive)
260 (message "Starting async-test-1...")
261 (async-start
262 ;; What to do in the child process
263 (lambda ()
264 (message "This is a test")
265 (sleep-for 3)
266 222)
267
268 ;; What to do when it finishes
269 (lambda (result)
270 (message "Async process done, result should be 222: %s" result)))
271 (message "Starting async-test-1...done"))
272
273 (defun async-test-2 ()
274 (interactive)
275 (message "Starting async-test-2...")
276 (let ((proc (async-start
277 ;; What to do in the child process
278 (lambda ()
279 (message "This is a test")
280 (sleep-for 3)
281 222))))
282 (message "I'm going to do some work here")
283 ;; ....
284 (message "Async process done, result should be 222: %s"
285 (async-get proc))))
286
287 (defun async-test-3 ()
288 (interactive)
289 (message "Starting async-test-3...")
290 (async-start
291 ;; What to do in the child process
292 (lambda ()
293 (message "This is a test")
294 (sleep-for 3)
295 (error "Error in child process")
296 222)
297
298 ;; What to do when it finishes
299 (lambda (result)
300 (message "Async process done, result should be 222: %s" result)))
301 (message "Starting async-test-1...done"))
302
303 (defun async-test-4 ()
304 (interactive)
305 (message "Starting async-test-4...")
306 (async-start-process "sleep" "sleep"
307 ;; What to do when it finishes
308 (lambda (proc)
309 (message "Sleep done, exit code was %d"
310 (process-exit-status proc)))
311 "3")
312 (message "Starting async-test-4...done"))
313
314 (provide 'async)
315
316 ;;; async.el ends here