I wrote the following emacs lisp procedure to kill a dead ansi-term buffer. It works well if called with M-x. Also, it appears to run correctly when the called in a living term buffer. However, dead buffers happily insert Q anyways. Why is that and how can I make it actually kill the buffer when the process is dead without calling M-x?
(defun terminal-burn-when-dead-or-insert-Q ()
(interactive)
(setq buf (current-buffer))
(if (not (process-live-p (get-buffer-process buf)))
(kill-buffer buf)
(insert "Q")))
(define-key term-raw-map (kbd "Q") #'terminal-burn-when-dead-or-insert-Q)
(define-key term-mode-map (kbd "Q") #'terminal-burn-when-dead-or-insert-Q)