1 ;;; async --- Asynchronous processing in Emacs
3 ;; Copyright (C) 2012 John Wiegley
5 ;; Author: John Wiegley <jwiegley@gmail.com>
6 ;; Created: 18 Jun 2012
9 ;; X-URL: https://github.com/jwiegley/emacs-async
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.
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.
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.
28 ;; Adds the ability to call asynchronous functions and process with ease. See
29 ;; the documentation for `async-start' and `async-start-process'.
34 "Simple asynchronous processing in Emacs"
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)
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
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\\)-\")
68 (or (null include-regexp)
69 (string-match include-regexp (symbol-name sym)))
71 (or exclude-regexp "-syntax-table\\'")
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)))))))
80 (defalias 'async-inject-environment 'async-inject-variables)
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
91 (funcall async-callback proc)
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))
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)
107 (funcall async-callback result)
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)))))))
117 (defun async--receive-sexp (&optional stream)
118 (let ((sexp (if async-send-over-pipe
119 (read (base64-decode-string (read stream)))
122 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
125 (defun async--insert-sexp (sexp)
126 (if async-send-over-pipe
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)))
137 (defun async--transmit-sexp (process sexp)
140 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
141 (async--insert-sexp sexp)
142 (process-send-region process (point-min) (point-max))))
144 (defun async-batch-invoke ()
145 "Called from the child Emacs process' command-line."
146 (setq async-in-child-emacs t)
149 (async--receive-sexp (unless async-send-over-pipe
150 command-line-args-left))))
153 (prin1 `(async-signal . ,err)))))
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))
161 (defun async-wait (future)
162 "Wait for FUTURE to become ready."
163 (while (not (async-ready future))
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."
171 (with-current-buffer (process-buffer future)
174 (kill-buffer (current-buffer)))))
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
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))
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:
198 ;; What to do in the child process
200 (message \"This is a test\")
204 ;; What to do when it finishes
206 (message \"Async process done, result should be 222: %s\"
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
213 (let ((proc (async-start
214 ;; What to do in the child process
216 (message \"This is a test\")
220 (message \"I'm going to do some work here\") ;; ....
222 (message \"Waiting on async process, result should be 222: %s\"
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):
232 (delete-file \"a remote file on a slow link\" nil))
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'."
241 (let ((procvar (make-symbol "proc")))
242 `(let* ((sexp ,start-func)
245 "emacs" (expand-file-name invocation-name
246 invocation-directory)
248 "-Q" "-l" ,(find-library-name "async")
249 "-batch" "-f" "async-batch-invoke"
250 ,(and async-send-over-pipe
252 (async--insert-sexp (list 'quote sexp))
254 ,(if async-send-over-pipe
255 `(async--transmit-sexp ,procvar (list 'quote sexp)))
258 (defun async-test-1 ()
260 (message "Starting async-test-1...")
262 ;; What to do in the child process
264 (message "This is a test")
268 ;; What to do when it finishes
270 (message "Async process done, result should be 222: %s" result)))
271 (message "Starting async-test-1...done"))
273 (defun async-test-2 ()
275 (message "Starting async-test-2...")
276 (let ((proc (async-start
277 ;; What to do in the child process
279 (message "This is a test")
282 (message "I'm going to do some work here")
284 (message "Async process done, result should be 222: %s"
287 (defun async-test-3 ()
289 (message "Starting async-test-3...")
291 ;; What to do in the child process
293 (message "This is a test")
295 (error "Error in child process")
298 ;; What to do when it finishes
300 (message "Async process done, result should be 222: %s" result)))
301 (message "Starting async-test-1...done"))
303 (defun async-test-4 ()
305 (message "Starting async-test-4...")
306 (async-start-process "sleep" "sleep"
307 ;; What to do when it finishes
309 (message "Sleep done, exit code was %d"
310 (process-exit-status proc)))
312 (message "Starting async-test-4...done"))
316 ;;; async.el ends here