Vim Tip #23: The Scratch Buffer

2019-08-23(Fri)

tags: Vim

Vim Tips

I should acknowledge immediately that I'm blundering around in a dark corner of Vim that I don't fully understand. Vim has a LOT of dark corners, and the only way to get to understand them is to try things and break stuff and learn. So if you follow my lead, you may well be doing something incorrectly. What's shown here is useful to me, so I'm going to detail what I did and you can decide for yourself.

First, what is a "scratch buffer?" Think of it as a temporary space for notes, like a physical scratch pad. Although with one significant caveat: if you close your Vim session, those notes are GONE. So why would you want this? I recently had to refactor a Groovy program, moving an array out of the file where it was called into an external data structure. It was called in several places, and I wanted to take notes about what to search for and what to replace it with. These notes held no value outside of this one editing session, so the scratch buffer worked great. It's also really good for copy-editing pieces of cut-and-paste text.

To take a look at Vim's opinion on scratch buffers and how to create one, see :help special-buffers. Creating a scratch buffer requires several steps, so I decided to wrap them in a function:

" store this in ~/.vim/plugin/Newscratch.vim
function Newscratch()
    execute 'tabnew '
    setlocal buftype=nofile
    setlocal bufhidden=hide
    setlocal noswapfile
endfunction

After you exit and re-enter Vim, typing :call Newscratch() will get you a scratch buffer on a new tab (I prefer tabs over buffer lists ...). To make this shorter, you can create a mapping:

" put this with your other mappings in the ~/.vimrc
command! -nargs=0 Ns call Newscratch()

I'm going to repeat an important point: close it and you lose it! (And Vim won't warn you that you haven't saved the buffer, because it CAN'T be saved.) Copy important stuff out to actual files.

Bibliography