mikeb
mikeb

Reputation: 11267

Emacs lisp key binding in shell mode not working

I have my emacs editor setup to run a shell when I press Ctrl-z. When inside of a shell buffer, I use Ctrl-z to clear the buffer by running the erase-buffer function. The code is being evaluated (when I Ctrl-h v and describe the shell-mode-map I can see that C-z is bound to clear-shell-buffer in shell mode. When I run the clear-shell-buffer with M-x the message says:

You can run the command clear-shell-buffer with <C-z>

However, when I type Ctrl-z in the shell it does not run the function or give any messages at all. Any idea why?

(defun clear-shell-buffer ()
  "Clear the contents of the current buffer"
  (interactive)
  (erase-buffer)
  ;;  (insert "/usr/games/fortune -a")
  (comint-send-input)
  )

(put 'erase-buffer 'disabled nil)
(eval-after-load 'shell
  '(define-key shell-mode-map [(\C-z)] 'clear-shell-buffer))

Upvotes: 0

Views: 252

Answers (1)

resueman
resueman

Reputation: 10613

This is happening because of the key binding being incorrect. You can verify this by doing C-h k C-z when in shell mode.

Instead of [(\C-z)], use one of these options:

  • [(?\C-z)]
  • [(control ?z)]
  • (kbd "C-z")

which will correctly set the key binding, and let you call the correct function with C-z

You can see a little bit of what's happening if you evaluate just the those statements. Here's the output I get for each

(define-key shell-mode-map [(\C-z)] 'clear-shell-buffer)
;;Output: (define-key shell-mode-map [(C-z)] (quote clear-shell-buffer))

(define-key shell-mode-map [(?\C-z)] 'clear-shell-buffer)
;;Output: (define-key shell-mode-map [(26)] (quote clear-shell-buffer))

You can see that the types differ for the key binding. Right now, you're passing a symbol, when you want to be passing a character code.

Upvotes: 1

Related Questions