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)
45 (defun async-inject-variables
46 (include-regexp &optional predicate exclude-regexp)
47 "Return a `setq' form that replicates part of the calling environment.
48 It sets the value for every variable matching INCLUDE-REGEXP and
49 also PREDICATE. It will not perform injection for any variable
50 matching EXCLUDE-REGEXP (if present). It is intended to be used
57 (insert ,(buffer-substring-no-properties (point-min) (point-max)))
58 ;; Pass in the variable environment for smtpmail
59 ,(async-inject-variables \"\\`\\(smtpmail\\|\\(user-\\)?mail\\)-\")
67 (or (null include-regexp)
68 (string-match include-regexp (symbol-name sym)))
70 (or exclude-regexp "-syntax-table\\'")
72 (let ((value (symbol-value sym)))
73 (when (or (null predicate)
74 (funcall predicate sym))
75 (setq bindings (cons `(quote ,value) bindings)
76 bindings (cons sym bindings)))))))
79 (defalias 'async-inject-environment 'async-inject-variables)
81 (defun async-when-done (proc &optional change)
82 "Process sentinal used to retrieve the value from the child process."
83 (when (eq 'exit (process-status proc))
84 (with-current-buffer (process-buffer proc)
85 (if (= 0 (process-exit-status proc))
86 (if async-callback-for-process
89 (funcall async-callback proc)
91 (kill-buffer (current-buffer))))
92 (set (make-local-variable 'async-callback-value) proc)
93 (set (make-local-variable 'async-callback-value-set) t))
94 (goto-char (point-max))
96 (let ((result (read (current-buffer))))
97 (if (and (listp result)
98 (eq 'async-signal (car result)))
99 (if (eq 'error (car (cdr result)))
100 (error (cadr (cdr result)))
101 (signal (cadr result)
105 (funcall async-callback result)
107 (kill-buffer (current-buffer))))
108 (set (make-local-variable 'async-callback-value) result)
109 (set (make-local-variable 'async-callback-value-set) t)))))
110 (set (make-local-variable 'async-callback-value) 'error)
111 (set (make-local-variable 'async-callback-value-set) t)
112 (error "Async process '%s' failed with exit code %d"
113 (process-name proc) (process-exit-status proc))))))
115 (defun async--receive-sexp (&optional stream)
116 (let ((sexp (read (base64-decode-string (read stream)))))
118 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
121 (defun async--insert-sexp (sexp)
122 (prin1 sexp (current-buffer))
123 ;; Just in case the string we're sending might contain EOF
124 (base64-encode-region (point-min) (point-max) t)
125 (goto-char (point-min)) (insert ?\")
126 (goto-char (point-max)) (insert ?\" ?\n))
128 (defun async--transmit-sexp (process sexp)
131 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
132 (async--insert-sexp sexp)
133 (process-send-region process (point-min) (point-max))))
135 (defun async-batch-invoke ()
136 "Called from the child Emacs process' command-line."
137 (setq async-in-child-emacs t)
140 (async--receive-sexp (unless async-send-over-pipe
141 command-line-args-left))))
144 (prin1 `(async-signal . ,err)))))
146 (defun async-ready (future)
147 "Query a FUTURE to see if the ready is ready -- i.e., if no blocking
148 would result from a call to `async-get' on that FUTURE."
149 (and (eq 'exit (process-status future))
150 async-callback-value-set))
152 (defun async-wait (future)
153 "Wait for FUTURE to become ready."
154 (while (not (async-ready future))
157 (defun async-get (future)
158 "Get the value from an asynchronously function when it is ready.
159 FUTURE is returned by `async-start' or `async-start-process' when
160 its FINISH-FUNC is nil."
162 (with-current-buffer (process-buffer future)
165 (kill-buffer (current-buffer)))))
168 (defun async-start-process (name program finish-func &rest program-args)
169 "Start the executable PROGRAM asynchronously. See `async-start'.
170 PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the
171 process object when done. If FINISH-FUNC is nil, the future
172 object will return the process object when the program is
174 (let* ((buf (generate-new-buffer (concat "*" name "*")))
175 (proc (apply #'start-process name buf program program-args)))
176 (with-current-buffer buf
177 (set (make-local-variable 'async-callback) finish-func)
178 (set-process-sentinel proc #'async-when-done)
179 (unless (string= name "emacs")
180 (set (make-local-variable 'async-callback-for-process) t))
184 (defmacro async-start (start-func &optional finish-func)
185 "Execute START-FUNC (often a lambda) in a subordinate Emacs process.
186 When done, the return value is passed to FINISH-FUNC. Example:
189 ;; What to do in the child process
191 (message \"This is a test\")
195 ;; What to do when it finishes
197 (message \"Async process done, result should be 222: %s\"
200 If FINISH-FUNC is nil or missing, a future is returned that can
201 be inspected using `async-get', blocking until the value is
204 (let ((proc (async-start
205 ;; What to do in the child process
207 (message \"This is a test\")
211 (message \"I'm going to do some work here\") ;; ....
213 (message \"Waiting on async process, result should be 222: %s\"
216 If you don't want to use a callback, and you don't care about any
217 return value form the child process, pass the `ignore' symbol as
218 the second argument (if you don't, and never call `async-get', it
219 will leave *emacs* process buffers hanging around):
223 (delete-file \"a remote file on a slow link\" nil))
226 Note: Even when FINISH-FUNC is present, a future is still
227 returned except that it yields no value (since the value is
228 passed to FINISH-FUNC). Call `async-get' on such a future always
229 returns nil. It can still be useful, however, as an argument to
230 `async-ready' or `async-wait'."
232 (let ((procvar (make-symbol "proc")))
233 `(let* ((sexp ,start-func)
236 "emacs" (expand-file-name invocation-name
237 invocation-directory)
239 "-Q" "-l" ,(find-library-name "async")
240 "-batch" "-f" "async-batch-invoke"
241 ,(and async-send-over-pipe
243 (async--insert-sexp (list 'quote sexp))
245 ,(if async-send-over-pipe
246 `(async--transmit-sexp ,procvar (list 'quote sexp)))
249 (defun async-test-1 ()
251 (message "Starting async-test-1...")
253 ;; What to do in the child process
255 (message "This is a test")
259 ;; What to do when it finishes
261 (message "Async process done, result should be 222: %s" result)))
262 (message "Starting async-test-1...done"))
264 (defun async-test-2 ()
266 (message "Starting async-test-2...")
267 (let ((proc (async-start
268 ;; What to do in the child process
270 (message "This is a test")
273 (message "I'm going to do some work here")
275 (message "Async process done, result should be 222: %s"
278 (defun async-test-3 ()
280 (message "Starting async-test-3...")
282 ;; What to do in the child process
284 (message "This is a test")
286 (error "Error in child process")
289 ;; What to do when it finishes
291 (message "Async process done, result should be 222: %s" result)))
292 (message "Starting async-test-1...done"))
294 (defun async-test-4 ()
296 (message "Starting async-test-4...")
297 (async-start-process "sleep" "sleep"
298 ;; What to do when it finishes
300 (message "Sleep done, exit code was %d"
301 (process-exit-status proc)))
303 (message "Starting async-test-4...done"))
307 ;;; async.el ends here