Search code examples
emacselisp

Kill Emacs's Async Shell Command buffer if command is terminated


Emacs does not kill the *Async Shell Command* buffer if the async command terminates. How can I force this behavior?


Solution

  • What you are looking for is Process Sentinels.

    The sentinel for *Async Shell Command* is shell-command-sentinel.

    You can advise it:

    (defun my-kill-buffer-when-done (process signal)
      (when (and (process-buffer process)
                 (memq (process-status process) '(exit signal)))
        (kill-buffer (process-buffer process))))
    
    (defun my-kill-async-buffer-when-done ()
      (let ((process (get-buffer-process "*Async Shell Command*")))
        (add-function :after (process-sentinel process) #'kill-buffer-when-done)))
    
    (add-function :after #'async-shell-command #'my-kill-async-buffer-when-done)
    

    PS. I did not test the above code, mostly because I think it is a horrible idea: you want to examine the content of *Async Shell Command* before killing it. However, I hope reading the code and links above will help you become a more proficient Emacs user.