Scratch buffers for Emacs

I often find myself needing to quickly work on some code that’s mostly unrelated to my task at hand. This comes up often when pair programming and code reviews, where you might want to illustrate a tactic without adding useless code to your current buffer.

Ordinarily, you’d use *scratch*, but it’s useful to have your scratch buffer use mode for the language you want to write code in, and *scratch* doesn’t fulfill this unless you’re hacking on emacs-lisp.

To this end, I created scratch-el, a bit of code for doing just this.

When you invoke it with M-x scratch, it gives you a scratch buffer with the same mode as your current buffer. So if you’re editing Python code, you get a *python* buffer which uses python-mode. If you’re in a shell, you get a shell-script-mode buffer, and so on.

If you invoke it with a prefix argument, as C-u M-x scratch, it will prompt you for the mode to use, which can be helpful if you want to noodle on a SQL query while editing your app code. There is tab completion support for all known major modes.

If you want to save the resulting work, it’s just a C-x C-w away.

2010/08/16
Previously On Atomized:

Discussion

Thanks for this. I had just started writing something like this for myself (just some functions to pop up scratch buffers in particular modes). This is much better.

Ed Singleton
2010/08/17

I have had scratch-pad-mode for almost 2 years. It looks like this: http://imagebin.org/110065. I bound it to C-h n. Unfortunately I just did have time to publish it :(

Leo
2010/08/17

Thanks, I like it. Simple and efficient.

Niels Giesen
2010/08/17

Nice idea. I’d suggest naming the buffers *(mode)-scratch* rather than *(mode)* to avoid possible clashes, though.

Phil
2010/08/17

That might be nice, but I’ve never once had that problem in practice.

Ian
2010/08/17

What about auto save feature with scratch buffers ? This is the reason I was reflected from using them – work can be lost (?)

Mariusz Nowak
2010/08/18

Here’s an alternate technique that lets (C-x b) setup the mode based on the buffer name which avoids having to learn a new command.

(setq default-major-mode (lambda ()
(let ((buffer-file-name (or buffer-file-name (buffer-name))))
(set-auto-mode))))

Then try

C-x b t.c

C-x b t.py

C-x b t.js

Jim
2010/08/19

I change the mode of my *scratch* buffer:
C-x b *scratch*
M-x cperl-mode

amoore
2010/08/19

Participate