]> code.delx.au - gnu-emacs-elpa/blob - async.el
Always base64 encode
[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 (read (base64-decode-string (read stream)))))
119 (if async-debug
120 (message "Received sexp {{{%s}}}" (pp-to-string sexp)))
121 (eval sexp)))
122
123 (defun async--insert-sexp (sexp)
124 (prin1 sexp (current-buffer))
125 ;; Just in case the string we're sending might contain EOF
126 (base64-encode-region (point-min) (point-max) t)
127 (goto-char (point-min)) (insert ?\")
128 (goto-char (point-max)) (insert ?\" ?\n))
129
130 (defun async--transmit-sexp (process sexp)
131 (with-temp-buffer
132 (if async-debug
133 (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp)))
134 (async--insert-sexp sexp)
135 (process-send-region process (point-min) (point-max))))
136
137 (defun async-batch-invoke ()
138 "Called from the child Emacs process' command-line."
139 (setq async-in-child-emacs t)
140 (condition-case err
141 (prin1 (funcall
142 (async--receive-sexp (unless async-send-over-pipe
143 command-line-args-left))))
144 (error
145 (backtrace)
146 (prin1 `(async-signal . ,err)))))
147
148 (defun async-ready (future)
149 "Query a FUTURE to see if the ready is ready -- i.e., if no blocking
150 would result from a call to `async-get' on that FUTURE."
151 (and (eq 'exit (process-status future))
152 async-callback-value-set))
153
154 (defun async-wait (future)
155 "Wait for FUTURE to become ready."
156 (while (not (async-ready future))
157 (sit-for 0.05)))
158
159 (defun async-get (future)
160 "Get the value from an asynchronously function when it is ready.
161 FUTURE is returned by `async-start' or `async-start-process' when
162 its FINISH-FUNC is nil."
163 (async-wait future)
164 (with-current-buffer (process-buffer future)
165 (prog1
166 async-callback-value
167 (kill-buffer (current-buffer)))))
168
169 (defun async-message-p (value)
170 "Return true of VALUE is an async.el message packet."
171 (and (listp value)
172 (plist-get value :async-message)))
173
174 (defun async-send (&rest args)
175 "Send the given messages to the asychronous Emacs PROCESS."
176 (let ((args (append args '(:async-message t))))
177 (if async-in-child-emacs
178 (if async-callback
179 (funcall async-callback args))
180 (async--transmit-sexp (car args) (list 'quote (cdr args))))))
181
182 (defun async-receive (&rest args)
183 "Send the given messages to the asychronous Emacs PROCESS."
184 (async--receive-sexp))
185
186 ;;;###autoload
187 (defun async-start-process (name program finish-func &rest program-args)
188 "Start the executable PROGRAM asynchronously. See `async-start'.
189 PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the
190 process object when done. If FINISH-FUNC is nil, the future
191 object will return the process object when the program is
192 finished."
193 (let* ((buf (generate-new-buffer (concat "*" name "*")))
194 (proc (apply #'start-process name buf program program-args)))
195 (with-current-buffer buf
196 (set (make-local-variable 'async-callback) finish-func)
197 (set-process-sentinel proc #'async-when-done)
198 (unless (string= name "emacs")
199 (set (make-local-variable 'async-callback-for-process) t))
200 proc)))
201
202 ;;;###autoload
203 (defmacro async-start (start-func &optional finish-func)
204 "Execute START-FUNC (often a lambda) in a subordinate Emacs process.
205 When done, the return value is passed to FINISH-FUNC. Example:
206
207 (async-start
208 ;; What to do in the child process
209 (lambda ()
210 (message \"This is a test\")
211 (sleep-for 3)
212 222)
213
214 ;; What to do when it finishes
215 (lambda (result)
216 (message \"Async process done, result should be 222: %s\"
217 result)))
218
219 If FINISH-FUNC is nil or missing, a future is returned that can
220 be inspected using `async-get', blocking until the value is
221 ready. Example:
222
223 (let ((proc (async-start
224 ;; What to do in the child process
225 (lambda ()
226 (message \"This is a test\")
227 (sleep-for 3)
228 222))))
229
230 (message \"I'm going to do some work here\") ;; ....
231
232 (message \"Waiting on async process, result should be 222: %s\"
233 (async-get proc)))
234
235 If you don't want to use a callback, and you don't care about any
236 return value form the child process, pass the `ignore' symbol as
237 the second argument (if you don't, and never call `async-get', it
238 will leave *emacs* process buffers hanging around):
239
240 (async-start
241 (lambda ()
242 (delete-file \"a remote file on a slow link\" nil))
243 'ignore)
244
245 Note: Even when FINISH-FUNC is present, a future is still
246 returned except that it yields no value (since the value is
247 passed to FINISH-FUNC). Call `async-get' on such a future always
248 returns nil. It can still be useful, however, as an argument to
249 `async-ready' or `async-wait'."
250 (require 'find-func)
251 (let ((procvar (make-symbol "proc")))
252 `(let* ((sexp ,start-func)
253 (,procvar
254 (async-start-process
255 "emacs" (expand-file-name invocation-name
256 invocation-directory)
257 ,finish-func
258 "-Q" "-l" ,(find-library-name "async")
259 "-batch" "-f" "async-batch-invoke"
260 ,@(unless async-send-over-pipe
261 '((with-temp-buffer
262 (async--insert-sexp (list 'quote sexp))
263 (buffer-string)))))))
264 ,@(if async-send-over-pipe
265 `((async--transmit-sexp ,procvar (list 'quote sexp))))
266 ,procvar)))
267
268 (defun async-test-1 ()
269 (interactive)
270 (message "Starting async-test-1...")
271 (async-start
272 ;; What to do in the child process
273 (lambda ()
274 (message "This is a test")
275 (sleep-for 3)
276 222)
277
278 ;; What to do when it finishes
279 (lambda (result)
280 (message "Async process done, result should be 222: %s" result)))
281 (message "Starting async-test-1...done"))
282
283 (defun async-test-2 ()
284 (interactive)
285 (message "Starting async-test-2...")
286 (let ((proc (async-start
287 ;; What to do in the child process
288 (lambda ()
289 (message "This is a test")
290 (sleep-for 3)
291 222))))
292 (message "I'm going to do some work here")
293 ;; ....
294 (message "Async process done, result should be 222: %s"
295 (async-get proc))))
296
297 (defun async-test-3 ()
298 (interactive)
299 (message "Starting async-test-3...")
300 (async-start
301 ;; What to do in the child process
302 (lambda ()
303 (message "This is a test")
304 (sleep-for 3)
305 (error "Error in child process")
306 222)
307
308 ;; What to do when it finishes
309 (lambda (result)
310 (message "Async process done, result should be 222: %s" result)))
311 (message "Starting async-test-1...done"))
312
313 (defun async-test-4 ()
314 (interactive)
315 (message "Starting async-test-4...")
316 (async-start-process "sleep" "sleep"
317 ;; What to do when it finishes
318 (lambda (proc)
319 (message "Sleep done, exit code was %d"
320 (process-exit-status proc)))
321 "3")
322 (message "Starting async-test-4...done"))
323
324 (defun async-test-5 ()
325 (interactive)
326 (message "Starting async-test-5...")
327 (let ((proc
328 (async-start
329 ;; What to do in the child process
330 (lambda ()
331 (message "This is a test, sending message")
332 (async-send :hello "world")
333 ;; wait for a message
334 (let ((msg (async-receive)))
335 (message "Child got message: %s"
336 (plist-get msg :goodbye)))
337 (sleep-for 3)
338 222)
339
340 ;; What to do when it finishes
341 (lambda (result)
342 (if (async-message-p result)
343 (message "Got hello from child process: %s"
344 (plist-get result :hello))
345 (message "Async process done, result should be 222: %s"
346 result))))))
347 (async-send proc :goodbye "everyone"))
348 (message "Starting async-test-5...done"))
349
350 (defun async-test-6 ()
351 (interactive)
352 (message "Starting async-test-6...")
353 (async-start
354 ;; What to do in the child process
355 `(lambda ()
356 ,(async-inject-variables "\\`user-mail-address\\'")
357 (format "user-mail-address = %s" user-mail-address))
358
359 ;; What to do when it finishes
360 (lambda (result)
361 (message "Async process done: %s" result))))
362
363 (provide 'async)
364
365 ;;; async.el ends here