Friday, October 1, 2010

Emacs - Clear Current Buffer

There are a few cases where clearing the current buffer is useful. For example,when using the *scratch* buffer a lot, or running a shell inside Emacs, being able to clear the screen can help the user stay organized. Since I'm often stuck in a Windows environment without Cygwin, running a shell inside Emacs is a great boost to productivity.

I recently found a method that works great. I'm sure there other, (possibly more elegant) solutions, but this gets the job done.

There are two functions to define for this solution; the best place for them is probably your .emacs file.

The first function, beginning-of-buffer(), from simply moves the point to the beginning of the buffer, leaving the mark wherever it happens to currently be.

(defun beginning-of-buffer()
"Move point to the beginning of the buffer."
(goto-char (point-min))

The second function, clear-buffer(), from Audacity Init-Nyquist, deletes everything in the buffer and moves the point to the beginning of the buffer.

(defun clear-buffer()
"Kill all of the text in the current buffer."
(clipboard-kill-region 1 (point-max))

It is of course possible to combine these two functions together if there is no reason to re-use beginning-of-buffer(). Once this is in your .emacs file, or has been run in Emacs, you can type M-x clear-buffer to clear the current buffer. It can also be mapped to a key combination like any other function.