Async shell command execution in GNU Emacs

In GNU Emacs if you execute shell command for instance using exec function the whole Editor freeze until shell command is finished. So I’ve written asynchronous version of exec:

(defun async-exec-command (command &rest success)
  (interactive "MExecute command: ")
  (let* ((buffer-name (generate-new-buffer-name "**shell**"))
         (buffer (get-buffer-create buffer-name))
         (process (apply #'start-process
                         (append (list buffer-name buffer)
                                 (split-string command " ")))))
    (lexical-let ((buffer buffer) (success (car success)) (command command))
      (set-process-sentinel process
                            (if success
                                (lambda (process str)
                                  (save-excursion
                                    (set-buffer buffer)
                                    (let ((content (buffer-string)))
                                      (kill-buffer buffer)
                                      (if (or (string= str "finished\n")
                                              (string-match "exited abnormally" str))
                                          (funcall success content)
                                        (message content)))))
                              (lambda (proces str)
                                (kill-buffer buffer)))))
    (concat "execute: " command)))

Published by

jcubic

I'm a web developer from Poland with a focus on JavaScript.

Leave a comment