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