Nicolas Martyanoff ā€” Brain dump

Clearing the Eshell Buffer

I have used the C-l shortcut in ZSH to clear the screen for as long as I can remember. When I started using Eshell, one of the first problems I encountered was the inability to clear the buffer. I like to remove the output of previous commands to be able to focus on the current one, so let us script Emacs once again.

After a quick look to the eshell module, it seems we can do that in two steps:

  1. Clear the entire buffer with (eshell/clear t).
  2. Recreate the prompt with (eshell-emit-prompt).

A non-obvious edge case is that it should be possible to hit C-l while typing a command without losing what was typed. For that, we have to keep a copy of the input content before clearing the screen and reinsert it after.

The result is the following function:

(defun g-eshell-clear ()
  (interactive)
  (let ((input (eshell-get-old-input)))
    (eshell/clear t)
    (eshell-emit-prompt)
    (insert input)))

We then write a hook which binds the function to C-l:

(defun g-eshell-init-keys ()
  (define-key eshell-mode-map (kbd "C-l") 'g-eshell-clear))

And register the hook:

(add-hook 'eshell-mode-hook 'g-eshell-init-keys)

Note that clearing the screen means removing shell history from the buffer. Not really an issue: instead of looking in the buffer, I use helm-eshell-history which is much more convenient.