]> code.delx.au - gnu-emacs-elpa/blob - async.el
* async-test.el: Update copyrights.
[gnu-emacs-elpa] / async.el
1 ;;; async --- Asynchronous processing in Emacs
2
3 ;; Copyright (C) 2012~2014 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 (decode-coding-string (base64-decode-string
122 (read stream)) 'utf-8-unix)))
123 (if async-debug
124 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
125 (setq sexp (read sexp))
126 (if async-debug
127 (message "Read sexp {{{%s}}}" (pp-to-string sexp)))
128 (eval sexp)))
129
130 (defun async--insert-sexp (sexp)
131 (prin1 sexp (current-buffer))
132 ;; Just in case the string we're sending might contain EOF
133 (encode-coding-region (point-min) (point-max) 'utf-8-unix)
134 (base64-encode-region (point-min) (point-max) t)
135 (goto-char (point-min)) (insert ?\")
136 (goto-char (point-max)) (insert ?\" ?\n))
137
138 (defun async--transmit-sexp (process sexp)
139 (with-temp-buffer
140 (if async-debug
141 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
142 (async--insert-sexp sexp)
143 (process-send-region process (point-min) (point-max))))
144
145 (defun async-batch-invoke ()
146 "Called from the child Emacs process' command-line."
147 (setq async-in-child-emacs t
148 debug-on-error async-debug)
149 (if debug-on-error
150 (prin1 (funcall
151 (async--receive-sexp (unless async-send-over-pipe
152 command-line-args-left))))
153 (condition-case err
154 (prin1 (funcall
155 (async--receive-sexp (unless async-send-over-pipe
156 command-line-args-left))))
157 (error
158 (prin1 (list 'async-signal err))))))
159
160 (defun async-ready (future)
161 "Query a FUTURE to see if the ready is ready -- i.e., if no blocking
162 would result from a call to `async-get' on that FUTURE."
163 (and (memq (process-status future) '(exit signal))
164 (with-current-buffer (process-buffer future)
165 async-callback-value-set)))
166
167 (defun async-wait (future)
168 "Wait for FUTURE to become ready."
169 (while (not (async-ready future))
170 (sit-for 0.05)))
171
172 (defun async-get (future)
173 "Get the value from an asynchronously function when it is ready.
174 FUTURE is returned by `async-start' or `async-start-process' when
175 its FINISH-FUNC is nil."
176 (async-wait future)
177 (with-current-buffer (process-buffer future)
178 (async-handle-result #'identity async-callback-value (current-buffer))))
179
180 (defun async-message-p (value)
181 "Return true of VALUE is an async.el message packet."
182 (and (listp value)
183 (plist-get value :async-message)))
184
185 (defun async-send (&rest args)
186 "Send the given messages to the asychronous Emacs PROCESS."
187 (let ((args (append args '(:async-message t))))
188 (if async-in-child-emacs
189 (if async-callback
190 (funcall async-callback args))
191 (async--transmit-sexp (car args) (list 'quote (cdr args))))))
192
193 (defun async-receive (&rest args)
194 "Send the given messages to the asychronous Emacs PROCESS."
195 (async--receive-sexp))
196
197 ;;;###autoload
198 (defun async-start-process (name program finish-func &rest program-args)
199 "Start the executable PROGRAM asynchronously. See `async-start'.
200 PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the
201 process object when done. If FINISH-FUNC is nil, the future
202 object will return the process object when the program is
203 finished."
204 (let* ((buf (generate-new-buffer (concat "*" name "*")))
205 (proc (let ((process-connection-type nil))
206 (apply #'start-process name buf program program-args))))
207 (with-current-buffer buf
208 (set (make-local-variable 'async-callback) finish-func)
209 (set-process-sentinel proc #'async-when-done)
210 (unless (string= name "emacs")
211 (set (make-local-variable 'async-callback-for-process) t))
212 proc)))
213
214 ;;;###autoload
215 (defmacro async-start (start-func &optional finish-func)
216 "Execute START-FUNC (often a lambda) in a subordinate Emacs process.
217 When done, the return value is passed to FINISH-FUNC. Example:
218
219 (async-start
220 ;; What to do in the child process
221 (lambda ()
222 (message \"This is a test\")
223 (sleep-for 3)
224 222)
225
226 ;; What to do when it finishes
227 (lambda (result)
228 (message \"Async process done, result should be 222: %s\"
229 result)))
230
231 If FINISH-FUNC is nil or missing, a future is returned that can
232 be inspected using `async-get', blocking until the value is
233 ready. Example:
234
235 (let ((proc (async-start
236 ;; What to do in the child process
237 (lambda ()
238 (message \"This is a test\")
239 (sleep-for 3)
240 222))))
241
242 (message \"I'm going to do some work here\") ;; ....
243
244 (message \"Waiting on async process, result should be 222: %s\"
245 (async-get proc)))
246
247 If you don't want to use a callback, and you don't care about any
248 return value form the child process, pass the `ignore' symbol as
249 the second argument (if you don't, and never call `async-get', it
250 will leave *emacs* process buffers hanging around):
251
252 (async-start
253 (lambda ()
254 (delete-file \"a remote file on a slow link\" nil))
255 'ignore)
256
257 Note: Even when FINISH-FUNC is present, a future is still
258 returned except that it yields no value (since the value is
259 passed to FINISH-FUNC). Call `async-get' on such a future always
260 returns nil. It can still be useful, however, as an argument to
261 `async-ready' or `async-wait'."
262 (require 'find-func)
263 (let ((procvar (make-symbol "proc")))
264 `(let* ((sexp ,start-func)
265 (,procvar
266 (async-start-process
267 "emacs" (file-truename
268 (expand-file-name invocation-name
269 invocation-directory))
270 ,finish-func
271 "-Q" "-l" ,(symbol-file 'async-batch-invoke 'defun)
272 "-batch" "-f" "async-batch-invoke"
273 (if async-send-over-pipe
274 "<none>"
275 (with-temp-buffer
276 (async--insert-sexp (list 'quote sexp))
277 (buffer-string))))))
278 (if async-send-over-pipe
279 (async--transmit-sexp ,procvar (list 'quote sexp)))
280 ,procvar)))
281
282 (defmacro async-sandbox(func)
283 "Evaluate FUNC in a separate Emacs process, synchronously."
284 `(async-get (async-start ,func)))
285
286 (provide 'async)
287
288 ;;; async.el ends here