1

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)
0

1 Answer 1

1
(define-key term-raw-map (kbd "Q") #'terminal-burn-when-dead-or-insert-Q)

That's definitely not going to do what you wanted it to in char mode. You need to send something to the process (like the regular binding term-send-raw does), not just insert some text into the buffer (which tells the process nothing).

It's also not clear from the question whether you'd loaded term.el before those define-key calls happened. If not, then those keymaps didn't exist (and you should have been seeing errors), in which case Q might never have been calling your custom command at all.

I would typically use:

(with-eval-after-load "term"
  (define-key term-mode-map ...))

Regarding your main question, when the process is killed, term-sentinel does this:

(with-current-buffer buffer
  ...
  ;; Get rid of local keymap.
  (use-local-map nil)
  (term-handle-exit (process-name proc) msg)
  ...)

I suggest you piggy-back onto the latter like so:

(define-advice term-handle-exit (:after (&rest _) Q-for-quit)
  "Make Q kill the buffer once the process is dead."
  (use-local-map (let ((map (make-sparse-keymap)))
                   (define-key map "Q" #'kill-current-buffer)
                   map)))

You don't need any of your existing code.

1
  • Thanks so much for the detailed explanation of what was going on!
    – wdkrnls
    Jul 7, 2020 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.